//package com.wushi.lenovo.asia5b.app_ui.other.dialog;
//
//import android.Manifest;
//import android.support.v7.widget.LinearLayoutManager;
//import android.support.v7.widget.RecyclerView;
//import android.text.TextUtils;
//import android.view.Gravity;
//import android.view.View;
//import android.widget.ImageView;
//import android.widget.Toast;
//
//import com.chad.library.adapter.base.BaseQuickAdapter;
//import com.luck.picture.lib.permissions.RxPermissions;
//import com.mvp.base.BaseAppCompatActivity;
//import com.mvp.base.BaseDialog;
//import com.mvp.utils.ToastUtil;
//import com.wushi.lenovo.asia5b.R;
//import com.wushi.lenovo.asia5b.app_config.BaseEvents;
//import com.wushi.lenovo.asia5b.app_model.credit.BaseHisModel;
//import com.wushi.lenovo.asia5b.app_ui.other.activity.PdfPreviewActivity;
//import com.wushi.lenovo.asia5b.app_ui.other.activity.PdfPreviewImageActivity;
//import com.wushi.lenovo.asia5b.app_ui.other.dialog.adapter.DownPdfAdapter;
//import com.wushi.lenovo.asia5b.app_utils.WFileUtil;
//import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;
//
//import org.greenrobot.eventbus.EventBus;
//
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.RandomAccessFile;
//import java.net.URL;
//import java.util.ArrayList;
//import java.util.List;
//
//import javax.net.ssl.HttpsURLConnection;
//
//import butterknife.BindView;
//import butterknife.OnClick;
//import io.reactivex.Observable;
//import io.reactivex.android.schedulers.AndroidSchedulers;
//import io.reactivex.disposables.Disposable;
//import io.reactivex.functions.Consumer;
//import io.reactivex.functions.Function;
//import io.reactivex.schedulers.Schedulers;
//
//import static timber.log.Timber.d;
//
///**
// * Created by zhangyuncai on 2019/1/24.
// * 下载交易记录pdf文档
// */
//public class DownPdfDialog extends BaseDialog {
//
//    @BindView(R.id.iv_cancelsure_ok)
//    ImageView iv_cancelsure_ok;
//    @BindView(R.id.rv_downloadtrans)
//    RecyclerView mRecyclerView;
//    private final List<BaseHisModel> mDatas = new ArrayList<>();
//    private DownPdfAdapter mAdapter;
//    BaseAppCompatActivity activity;
//    private Disposable subscribe;
//
//    public DownPdfDialog(BaseAppCompatActivity activity) {
//        super(activity);
//        this.activity = activity;
//    }
//
//    public <T extends BaseHisModel> void setDatas(List<T> list) {
//        if (list != null) {
//            mDatas.clear();
//            mAdapter.addData(list);
//        }
//    }
//
//    public <T extends BaseHisModel> void setModel(T model) {
//        if (model != null) {
//            mDatas.clear();
//            mAdapter.addData(model);
//        }
//    }
//
//    @Override
//    protected int getLayoutId() {
//        return R.layout.dialog_downpdf;
//    }
//
//    @Override
//    protected void initView() {
//        mAdapter = new DownPdfAdapter(mDatas);
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//        mRecyclerView.setAdapter(mAdapter);
//        setCanceledOnTouchOutside(false);
//    }
//
//    /**
//     * 查看pdf
//     *
//     * @param filePath 预览PDF文件路径
//     * @param orderNo  预览PDF订单号
//     */
//    private void watchPdf(String filePath, String orderNo) {
//        if (filePath.endsWith(".pdf")) {
//            PdfPreviewActivity.startPdfPreviewActivity(getContext(), filePath, orderNo);
//        } else {
//            PdfPreviewImageActivity.startPdfPreview2Activity(getContext(), filePath, orderNo);
//        }
//    }
//
//
//    @Override
//    protected void initListener() {
//        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                BaseHisModel model = mAdapter.getItem(position);
//                if (view.getId() == R.id.iv_downpdf_downicon) {
//                    new RxPermissions(activity)
//                            .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                            .subscribe(aBoolean -> {
//                                if (aBoolean) {
//                                    if (!TextUtils.isEmpty(model.getPdf_download_path()) || !TextUtils.isEmpty(model.getReceipt_image_path())) {
//                                        downloadPdf(model);
//                                    } else {
//                                        ToastUtil.showToast(getString(R.string.addressempty));
//                                    }
//                                } else {
//                                    ToastUtil.showToast(getString(R.string.permission_error1));
//                                    CrashHelper.postCatchedException(new Throwable(getString(R.string.permission_error1)));
//                                }
//                            });
//
//                } else if (view.getId() == R.id.tv_downpdf_view) {
//                    Object tag = view.getTag();
//                    if (tag != null && tag instanceof String) {
//                        String filePath = (String) tag;
//                        watchPdf(filePath, model.getReference_number());
//                        dismiss();
//                    } else {
//                        ToastUtil.showToast(getString(R.string.addressempty));
//                    }
//                }
//            }
//        });
//    }
//
//    private final int CONNECT_TIMEOUT = 300 * 1000;//下载文件可以给5分钟
//
//    private void downloadPdf(BaseHisModel model) {
//        //                            String fileName = connection.getHeaderField("Content-Disposition");
////                            Timber.d("--->>>>>>>>---fileName:" + fileName);
//        subscribe = Observable.just(model)
//                .map(new Function<BaseHisModel, String>() {
//                    @Override
//                    public String apply(BaseHisModel model) throws Exception {
//                        String downloadUrl = null;
//                        String filePath = null;
//                        if (!TextUtils.isEmpty(model.getPdf_download_path())) {
//                            filePath = WFileUtil.createPdfPath(activity, model.getReference_number());
//                            downloadUrl = model.getPdf_download_path();
//                        } else {
//                            filePath = WFileUtil.createImagePath(activity, model.getReference_number());
//                            downloadUrl = model.getReceipt_image_path();
//                        }
//                        d("--->>>>>>>>---保存地址:" + filePath);
//                        InputStream inputStream = null;
//                        RandomAccessFile randomAccessFile = null;
//                        HttpsURLConnection connection = null;
//                        try {
//                            URL url = new URL(downloadUrl);
////                            connection = (HttpsURLConnection) url.openConnection();
//                            connection = (HttpsURLConnection) url.openConnection();
//                            connection.setRequestMethod("GET");
//                            connection.setReadTimeout(CONNECT_TIMEOUT);
//                            connection.setConnectTimeout(CONNECT_TIMEOUT);
//                            connection.setRequestProperty("Accept-Encoding", "identity"); //不要使用gzip方式,添加这行代码
//                            connection.connect();
//                            int responseCode = connection.getResponseCode();
//                            d("--->>>>>>>>---请求code:" + responseCode);
//
////                            String fileName = connection.getHeaderField("Content-Disposition");
////                            Timber.d("--->>>>>>>>---fileName:" + fileName);
//                            inputStream = connection.getInputStream();
//                            int contentLength = connection.getContentLength();//文件总大小
//                            randomAccessFile = new RandomAccessFile(filePath, "rwd");
//                            byte[] buffer = new byte[1024 * 4];
//                            int length = 0;
//                            int xiazaiLength = 0;
//                            int progress = 0;
//                            while ((length = inputStream.read(buffer)) != -1) {
//                                randomAccessFile.write(buffer, 0, length);
//                                xiazaiLength += length;
//                                d("--->>>>>>>>---" + String.format("xiazaiLength:%d,contentLength:%d", xiazaiLength, contentLength));
//                                try {
//                                    int i = (int) ((xiazaiLength * 100f) / (contentLength * 1f));
//                                    if (progress != i) {
//                                        progress = i;
//                                        if (i >= 0 && i <= 100) {
//                                            activity.showLoadingBar(progress + "%");
//                                        }
//                                    }
//                                    d("--->>>>>>>>---i:" + i);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        } catch (Exception e) {
//                            filePath = "";
//                            e.printStackTrace();
//                            CrashHelper.postCatchedException(e.getCause());
//                        }
//                        if (inputStream != null) {
//                            inputStream.close();
//                        }
//                        if (connection != null) {
//                            connection.disconnect();
//                        }
//                        if (randomAccessFile != null) {
//                            try {
//                                randomAccessFile.close();
//                            } catch (IOException e) {
//                                filePath = "";
//                                e.printStackTrace();
//                                CrashHelper.postCatchedException(e.getCause());
//                            }
//                        }
//                        return filePath;
//                    }
//                })
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnSubscribe(disposable -> {
//                    activity.showLoadingBar(getString(R.string.downloading));
//                })
//                .doAfterTerminate(() -> {
//                    activity.dismissLoadingBar("all");
//                })
//                .subscribe(new Consumer<String>() {
//                    @Override
//                    public void accept(String s) throws Exception {
//                        if (!TextUtils.isEmpty(s)) {
//                            String toast = getString(R.string.save_success) + ":" + s;
//                            Toast.makeText(getContext(), toast, Toast.LENGTH_LONG).show();
//                            mAdapter.notifyDataSetChanged();
//                            watchPdf(s, model.getReference_number());
//                            EventBus.getDefault().post(new BaseEvents.DownPdfEvent(model.getReference_number()));
////                            dismiss();
//                        } else {
//                            ToastUtil.showToast(getString(R.string.save_fail));
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        throwable.printStackTrace();
//                        CrashHelper.postCatchedException(throwable);
//                    }
//                });
//    }
//
//    @OnClick({R.id.iv_cancelsure_ok})
//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.iv_cancelsure_ok: {
//                dismiss();
//            }
//            break;
//            default:
//                break;
//        }
//
//    }
//
//    @Override
//    public void dismiss() {
//        if (subscribe != null) {
//            subscribe.dispose();
//        }
//        super.dismiss();
//    }
//
//    @Override
//    protected int getGravity() {
//        return Gravity.CENTER;
//    }
//
//    @Override
//    protected int getWidthStyle() {
//        return getScreenWidth(0.7f);
//    }
//}
